import { Singleton } from "./base/Singleton"

interface IItem {
    ctx: unknown,
    fun: Function
}
export enum EEventType {
    test,
    /** 心跳,每秒广播一次 */
    heartbeat,
    /** 抽卡结果通知 */
    dawCardResoult,
}
/** 事件管理器 */
export class EventManager extends Singleton {

    static get Ins() {
        return super.GetInstance<EventManager>()
    }

    private map: Map<EEventType, IItem[]> = new Map()

    /** 注册 */
    on(name: EEventType, fun: Function, ctx: unknown) {
        if (this.map.has(name)) {
            this.map.get(name).push({ ctx, fun })
        } else {
            this.map.set(name, [{ ctx, fun }])
        }
    }

    /** 取消注册 */
    off(name: EEventType, fun: Function, ctx: unknown) {
        if (this.map.has(name)) {
            const index = this.map.get(name).findIndex(v => v.fun === fun && v.ctx === ctx)
            index > -1 && this.map.get(name).splice(index, 1)
        }
    }

    /** 移除所有上下文相关的事件 */
    offByCtx(ctx: unknown) {
        this.map.forEach(itemArr => {
            for (let index = itemArr.length - 1; index >= 0; index--) {
                if (ctx === itemArr[index].ctx) {
                    itemArr.splice(index, 1)
                }
            }
        })
    }

    /** 发送 */
    emit(name: EEventType, ...arg: any) {
        if (this.map.has(name)) {
            this.map.get(name)?.forEach(({ fun, ctx }) => {
                fun.apply(ctx, arg)
            })
        }
    }

    clear() {
        this.map = new Map()
    }
}